package com.oot.twitter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.oot.twitter.R;
import com.oot.twitter.Twitter;
import com.oot.twitter.ConnectionTwitter;

public class GCMIntentService extends GCMBaseIntentService {

	static final String SENDER_ID = "507076552906";
	public static String TAG = "GCMIntentService";
	
	public GCMIntentService() {
		super(SENDER_ID);
	}

	@Override
	protected void onError(Context context, String message) {
		Log.e(TAG, message);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		String message = intent.getStringExtra("message");
		generateNotification(context, message);
		Log.d(TAG, message);
	}

	@Override
	protected void onRegistered(Context context, String reg_id) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    	nameValuePairs.add(new BasicNameValuePair("gcm_id", reg_id));
    	
    	ConnectionTwitter.sendRequest(ConnectionTwitter.REG_GCM_ID, nameValuePairs);
	}

	@Override
	protected void onUnregistered(Context context, String reg_id) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    	nameValuePairs.add(new BasicNameValuePair("gcm_id", reg_id));
    	
    	ConnectionTwitter.sendRequest(ConnectionTwitter.UNREG_GCM_ID, nameValuePairs);
	}
	
	/**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
                context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
        String title = context.getString(R.string.app_name);
        Intent notificationIntent = new Intent(context, Twitter.class);
        
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent =
                PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(0, notification);
    }
}
